package org.feng.parser;

import lombok.extern.slf4j.Slf4j;
import org.feng.entity.TableMetaData;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.jdbc.support.rowset.SqlRowSetMetaData;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * MySql 元数据解析实现
 *
 * @version v1.0
 * @author: fengjinsong
 * @date: 2022年07月23日 09时21分
 */
@Slf4j
@Service
public class MysqlDmlParserImpl implements MysqlDmlParser {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public TableMetaData parser(String tableName) {
        TableMetaData tableMetaData = new TableMetaData();
        tableMetaData.setTableName(tableName);

        SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet("select * from " + tableName + " limit 0");
        SqlRowSetMetaData metaData = sqlRowSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        List<TableMetaData.ColumnInfo> columnInfos = new ArrayList<>(columnCount);
        for (int index = 1; index <= columnCount; index++) {
            // 列名
            String columnName = metaData.getColumnName(index);
            // 列类型名
            String columnClassName = metaData.getColumnClassName(index);
            // 列信息
            TableMetaData.ColumnInfo columnInfo = new TableMetaData.ColumnInfo();
            columnInfo.setName(columnName);
            columnInfo.setFullTypeName(columnClassName);
            columnInfos.add(columnInfo);
        }
        tableMetaData.setColumnInfos(columnInfos);
        return tableMetaData;
    }
}
